<template>
  <div>
    <a-form
      ref="manaPlanFormRef"
      class="mana-plan-form"
      :label-col="{ style: { width: '105px' } }"
      :disabled="isPushed"
      :model="updatedData"
    >
      <div class="mana-plan-item-info" v-for="(item, index) in updatedData" :key="index">
        <div style="display: flex; place-content: center space-between; margin-bottom: 4px">
          <a-form-item label="提醒时间" :rules="[{ required: true, message: '请输入提醒时间' }]">
            <div style="display: flex; align-items: center">
              <div style="display: flex; align-items: center">
                第
                <a-input-number
                  style="margin: 0 8px"
                  :min="1"
                  :precision="0"
                  v-model:value="item.cronCycle"
                  @change="(value) => changeTemCronCycleDebounced(item, value)"
                  :disabled="
                    item.sendTime
                      ? new Date().getTime() > new Date(item.sendTime).getTime()
                      : false || isPushed
                  "
                />
                天提醒一次
              </div>
              <a-date-picker
                :showToday="false"
                style="margin-left: 24px"
                v-model:value="item.sendTime"
                :disabled="
                  item.sendTime
                    ? new Date().getTime() > new Date(item.sendTime).getTime()
                    : false || isPushed
                "
                @change="(value) => changeTemSendTime(item, value)"
                :disabled-date="
                  (current) =>
                    !current ||
                    current < dayjs() ||
                    current <= dayjs(props.startTime) ||
                    current > dayjs(props.expiredTime)
                "
                :allowClear="false"
              />
            </div>
          </a-form-item>
          <a-button
            type="link"
            danger
            @click="removePlanItem(index)"
            :disabled="
              isPushed || item.sendTime
                ? new Date().getTime() > new Date(item.sendTime).getTime()
                : false
            "
          >
            删除
          </a-button>
        </div>
        <div
          style="padding-top: 16px; margin: 0 16px; background: #f7f8fa; border: 1px solid #e5e6eb"
        >
          <a-form-item label="当前模板库">
            <div style="display: flex; align-content: center">
              <a-space :size="[0, 0]">
                <span
                  @click="changeTemplate(item, '公共模板')"
                  :class="
                    item.templateAffiliation == '公共模板'
                      ? 'template-col template-col-active'
                      : 'template-col'
                  "
                  >健康处方模板库</span
                >
                <span
                  @click="changeTemplate(item, '个人模板')"
                  :class="
                    item.templateAffiliation == '个人模板'
                      ? 'template-col template-col-active'
                      : 'template-col'
                  "
                  >个人模板库</span
                >
                <span
                  @click="changeTemplate(item, 'AI生成')"
                  :class="
                    item.templateAffiliation == 'AI生成'
                      ? 'template-col template-col-active'
                      : 'template-col'
                  "
                  >AI生成</span
                >
              </a-space>
            </div>
          </a-form-item>
          <div v-if="item.templateAffiliation == 'AI生成'">
            <a-form-item>
              <div style="display: flex; align-items: center">
                <template v-if="item.aiStatus == 30">
                  <img class="ai-state-icon" src="@/assets/health/ai-error.png" alt="" />
                </template>
                <template v-if="!item.aiStatus || item.aiStatus == 20 || item.aiStatus == 10">
                  <img class="ai-state-icon" src="@/assets/health/ai-normal.png" alt="" />
                </template>
                <span>{{ item.aiCodeLabel }}</span>
                <a-button
                  type="primary"
                  @click="regenerate(item)"
                  style="margin-left: 12px"
                  v-if="!item.aiStatus || item.aiStatus == 30"
                >
                  {{ transformAISattus(item) }}
                </a-button>
                <template v-if="item.aiStatus == 40">
                  <div style="display: flex; align-items: center; margin-left: 12px">
                    <img
                      style="width: 16px; height: 16px"
                      src="@/assets/health/loading.png"
                      alt=""
                    />
                    <a-button type="link" @click="regenerate(item)" style="padding-left: 8px">
                      重新生成
                    </a-button>
                  </div>
                </template>
                <a-button
                  type="primary"
                  v-if="item.aiStatus == 40"
                  @click="showAiDetail(item, index)"
                >
                  查看AI生成方案
                </a-button>
              </div>
            </a-form-item>
            <!-- <a-form-item>
              <span>{{ item.aiCodeLabel }}</span>
              <a-button type="link" @click="regenerate(item)">
                {{ transformAISattus(item) }}
              </a-button>
            </a-form-item> -->
          </div>
          <template v-if="item.templateAffiliation != 'AI生成'">
            <a-form-item label="选择模板" :rules="[{ required: true, message: '选择模板' }]">
              <a-select
                v-model:value="item.templateId"
                placeholder="请选择模板"
                :options="item.templateList"
                @change="templateChange(item, $event, index)"
                showSearch
                :disabled="isPushed || new Date().getTime() > new Date(item.sendTime).getTime()"
              />

              <a-button
                type="link"
                @click="showIndividual(item)"
                :disabled="isPushed || new Date().getTime() > new Date(item.sendTime).getTime()"
              >
                保存当前已修改方案到个人模板
              </a-button>
            </a-form-item>
          </template>
          <a-form-item
            label="提醒内容模板"
            :rules="[{ required: true, message: '请输入提醒内容模板', whitespace: true }]"
          >
            <div style="display: flex; align-items: start; padding-right: 16px">
              <a-textarea
                v-model:value="item.content"
                style="width: 100%"
                :autoSize="{ minRows: 5, maxRows: 10 }"
                :maxlength="5000"
                show-count
                :disabled="isPushed || new Date().getTime() > new Date(item.sendTime).getTime()"
              />

              <!-- <a-button type="primary" @click="aiSetBtn">AI生成</a-button> -->
            </div>
          </a-form-item>
        </div>
      </div>
      <a-button
        @click="addPlanItem"
        :icon="h(PlusOutlined)"
        type="primary"
        ghost
        v-if="!isPushed"
        class="add-plan-item"
      >
        添加
      </a-button>
    </a-form>

    <!-- 个人模板保存 -->
    <a-modal
      v-model:open="individualOpen"
      title="保存当前方案到个人模板"
      :maskClosable="false"
      :destroyOnClose="true"
    >
      <a-form ref="individualForm" :model="individualFormData" style="margin-top: 14px">
        <div style="margin-bottom: 16px; font-weight: bold">{{ individualName }}</div>
        <a-form-item
          name="templateName"
          :rules="[{ required: true, message: '请输入模板名称', whitespace: true }]"
        >
          <a-auto-complete
            style="width: 100%"
            placeholder="请输入模板名称"
            :options="individualTemplateList"
            v-model:value="individualFormData.templateName"
            :filterOption="
              (inputValue, option) =>
                option.value.toUpperCase().indexOf(individualFormData.templateName.toUpperCase()) >=
                0
            "
            @blur="
              (value) => {
                individualFormData.templateName = individualFormData.templateName.replace(
                  /\s+/g,
                  ''
                )
              }
            "
          />
          <span
            v-if="
              individualTemplateList.findIndex((item) => {
                return item.value === individualFormData.templateName
              }) >= 0
            "
            style="color: red"
            >您当前选择的是已存在的模板，保存将覆盖原有模板内容</span
          >
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="individualOpen = false">取消</a-button>
        <a-button type="primary" @click="saveIndividual">保存</a-button>
      </template>
    </a-modal>
    <AiDetail ref="aiDetailRef" @setPlan="setAiPlan" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h, defineEmits, watchEffect } from 'vue'
import { PlusOutlined, RedoOutlined } from '@ant-design/icons-vue'
import store from '@/store'
import { getTemplateDetailList, TemplateAddOrUpdate } from '@/api/healthManaWorkbench/index'
import { message } from 'ant-design-vue'
import { getAiRecommendScheme, getAiRecommendSchemeDetail } from '@/api/healthManaWorkbench/index'
import AiDetail from './AiDetail.vue'
import dayjs from 'dayjs'
import { debounce } from 'lodash'

const manaPlanFormRef = ref()
const props = defineProps<{
  isPushed: boolean
  prescriptionData: any[]
  empi: string
  diseaseType: string
  startTime: string
  expiredTime: string
}>()

const userId = ref()
const templateDataList = ref()
const aiCodeLabel = ref<string>('')
const AITaskStatus = ref<any>()

// 模板
const individualTemplateList = ref()
const individualOpen = ref<boolean>(false)
const individualName = ref<string>('')
const individualFormData = reactive({
  templateName: '',
  templateType: '',
  content: '',
  data: {}
})

const AIHealthContent = ref<string>('')
const emit = defineEmits(['update:prescriptionData'])

const updatedData = ref<any>([])
onMounted(async () => {
  userId.value = store.userApp.userInfo.id

  templateDataList.value = await getTemplateList(null, null)

  setTimeout(() => {
    updatedData.value = [...props.prescriptionData]
    if (updatedData.value) {
      updatedData.value.forEach((item: any) => {
        if (item.templateAffiliation == 'AI生成') {
          item.AIContent = JSON.parse(JSON.stringify(item.content))
          aiGenerateStatus(item)
        }
      })
    }
  }, 300)
})

watchEffect(() => {
  if (props.prescriptionData && props.prescriptionData.length > 0) {
    updatedData.value = [...props.prescriptionData]
  }
})

const changeTemCronCycleDebounced = debounce((item, value) => {
  if (value) {
    const newTime = dayjs(props.startTime).add(value, 'day')
    const lastTime = dayjs(props.expiredTime)
    if (newTime.isBefore(dayjs())) {
      item.cronCycle = item.cronCycleInit
      if (item.cronCycle) {
        item.sendTime = dayjs(props.startTime).add(item.cronCycle, 'day')
      } else {
        item.sendTime = ''
      }
      message.error('过去的时间不支持输入，请重新修改')
      return
    }

    if (newTime.isAfter(lastTime)) {
      item.cronCycle = item.cronCycleInit
      if (item.cronCycle) {
        item.sendTime = dayjs(props.startTime).add(item.cronCycle, 'day')
      } else {
        item.sendTime = ''
      }
      message.error('超过会员过期时间不支持输入，请重新修改')
      return
    }

    changeTemCronCycle(item, value)
  } else {
    item.sendTime = ''
  }
}, 1000)
// 时间天改变
const changeTemCronCycle = (data, value) => {
  data.sendTime = dayjs(props.startTime).add(value, 'day')
}

const changeTemSendTime = (data, value) => {
  const time = dayjs(value)
  data.cronCycle = time.diff(dayjs(props.startTime), 'day')
}

const removePlanItem = (index: any) => {
  updatedData.value.splice(index, 1) // 删除指定项
  updatedData.value = [...updatedData.value]
  emit('update:prescriptionData', updatedData.value)
}

// 模板切换
const changeTemplate = (data, type) => {
  if (props.isPushed || new Date().getTime() > new Date(data.sendTime).getTime()) {
    return
  } else {
    if (data.templateAffiliation == type) {
      //
    } else {
      data.templateAffiliation = type

      if (type == 'AI生成') {
        aiGenerateStatus(data)
        if (data.AIContent) {
          data.content = JSON.parse(JSON.stringify(data.AIContent))
        } else {
          data.content = ''
        }
      } else {
        data.templateList = templateDataList.value.filter((tem) => {
          if (type == '个人模板') {
            return (
              tem.templateType == data.templateType &&
              tem.templateAffiliation == type &&
              tem.creator == userId.value
            )
          } else {
            return tem.templateType == data.templateType && tem.templateAffiliation == type
          }
        })

        if (data.oldTemplateAffiliation != type) {
          data.templateId = data.templateList.length > 0 ? data.templateList[0].id : undefined
        } else {
          data.templateId = data.oldTemeplateId
        }

        const temData: any = data.templateList.find((tem) => {
          return tem.id == data.templateId
        })

        data.content = temData ? temData.content : ''
      }
    }
  }
}

const transformAISattus = (data: any) => {
  switch (data.aiStatus) {
    case 10:
      data.aiCodeLabel = '可通过AI大模型为用户生成健康处方'
      return ''
    case 20:
      data.aiCodeLabel = '正在根据用户健康数据，生成AI健康处方...'
      return ''
    case 30:
      data.aiCodeLabel = 'AI生成失败，请重新生成'
      return '重新生成'
    case 40:
      data.aiCodeLabel = '以下方案由AI依据用户健康数据生成，请审核确认'
      return ''
    default:
      data.aiCodeLabel = '可通过AI大模型为用户生成健康处方'
      return 'AI生成'
  }
}

// 查看ai生成的方案
const aiDetailRef = ref()
const aiDetailIndex = ref()
const showAiDetail = (data, index) => {
  const res = JSON.parse(JSON.stringify(data.AITaskData))
  aiDetailIndex.value = index
  aiDetailRef.value.init(res, 'health')
}

// 使用ai方案
const setAiPlan = (data: any) => {
  updatedData.value[aiDetailIndex.value].content = data.content
}

const addPlanItem = () => {
  updatedData.value.push({
    templateAffiliation: '公共模板',
    cronCycle: '',
    content: '',
    templateId: undefined,
    templateType: '健康处方',
    templateList: templateDataList.value.filter((tem) => {
      return tem.templateType == '健康处方' && tem.templateAffiliation == '公共模板'
    }),
    platformId: store.userStore.platformId
  })

  emit('update:prescriptionData', updatedData.value)
}

// 选择模板切换
const templateChange = (data, e, index) => {
  // 根据选择的模板更新内容
  const selectedTemplate = data.templateList.find((tem) => tem.id == e)
  data.content = selectedTemplate ? selectedTemplate.content : ''
  data.templateId = e

  updatedData.value[index] = { ...data }

  emit('update:prescriptionData', updatedData.value)
}

// 展示个人模板保存
const showIndividual = (data) => {
  // 模板类型判断
  if (!data.content) {
    message.error('健康处方方案请填写完整')
  } else {
    individualTemplateList.value = []
    nextTick(() => {
      individualOpen.value = true
      if (individualForm.value) {
        individualForm.value.resetFields()
      }
      individualFormData.templateName = ''
      individualName.value = '健康处方个人模板库'
      individualFormData.templateType = '健康处方'
      individualFormData.content = data.content
      individualFormData.data = data // 需要保存的模板数据
      const listData = templateDataList.value.filter((tem) => {
        return (
          tem.templateType == '健康处方' &&
          tem.templateAffiliation == '个人模板' &&
          tem.creator == userId.value
        )
      })
      listData.forEach((item) => {
        individualTemplateList.value.push({
          value: item.templateName,
          label: item.templateName
        })
      })
    })
  }
}

// 个人模板保存
const individualForm = ref()
const saveIndividual = () => {
  individualForm.value.validate().then(() => {
    // 对应模板类型的所有个人模板数据
    const templateData = templateDataList.value.filter((tem) => {
      return (
        tem.templateType == individualFormData.templateType &&
        tem.templateAffiliation == '个人模板' &&
        tem.creator == userId.value
      )
    })
    const temContent = individualFormData.data.content
    individualFormData.templateName = individualFormData.templateName.replace(/\s+/g, '')
    const data = {
      id: null,
      templateName: individualFormData.templateName,
      templateType: individualFormData.templateType,
      content: temContent,
      templateAffiliation: '个人模板',
      platformId: store.userStore.platformId
    }
    if (templateData.length > 0) {
      const someData = templateData.filter((item) => {
        return item.templateName === individualFormData.templateName
      })
      data.id = someData.length > 0 ? someData[0].id : null
    }
    TemplateAddOrUpdate(data).then(async (res) => {
      individualOpen.value = false
      templateDataList.value = await getTemplateList(null, null)
      updatedData.value.map((item) => {
        item.templateList = templateDataList.value.filter((tem) => {
          return (
            tem.templateType == individualFormData.templateType &&
            tem.templateAffiliation == '个人模板' &&
            tem.creator == userId.value
          )
        })
      })
      message.success('保存成功')
      emit('update:prescriptionData', updatedData.value)
    })
  })
}

const regenerate = async (data: any) => {
  if ([30, 40].includes(data.aiStatus) || !data.aiStatus) {
    aiGenerateApi(data)
  }
}

// 查询Ai生成的状态
const aiGenerateStatus = (data) => {
  getAiRecommendScheme({
    empi: props.empi,
    code: 'PRESCRIPTION',
    diseaseType: props.diseaseType
  }).then((res: any) => {
    if (res.data) {
      data.aiStatus = res.data.status
      const content = res.data.content ? JSON.parse(res.data.content) : ''
      data.AITaskData = content
    } else {
      data.aiStatus = -1
    }
    transformAISattus(data)
  })
}

// ai生成方案
const aiGenerate = (data) => {
  getAiRecommendScheme({
    empi: props.empi,
    code: 'PRESCRIPTION',
    diseaseType: props.diseaseType
  }).then((res: any) => {
    if (res.data) {
      data.aiStatus = res.data.status
      // AITaskStatus.value = res.data.status
      const content = res.data.content ? JSON.parse(res.data.content) : ''
      data.AITaskData = content
    }
    transformAISattus(data)
  })
}

// 调用ai生成
const aiGenerateApi = (data) => {
  getAiRecommendSchemeDetail({
    empi: props.empi,
    code: 'PRESCRIPTION',
    diseaseType: props.diseaseType
  }).then(() => {
    data.aiStatus = 20
    // AITaskStatus.value = 20
    // data.content = ''
    transformAISattus(data)
  })
}

// 根据方案类型 模板类型获取响应的列表
const getTemplateList = async (templateType, templateAffiliation) => {
  let data: any = []
  const res = await getTemplateDetailList({
    templateType: templateType,
    templateAffiliation: templateAffiliation,
    platformId: store.userStore.platformId
  })

  res.data.map((item: any) => {
    item.label = item.templateName
    item.value = item.id
  })
  data = res.data
  return data
}
</script>
<style lang="less" scoped>
.mana-plan-item-info {
  padding: 16px 0;
  margin-bottom: 16px;
  border: 1px solid #e5e5e5;
}

.mana-plan-form .ant-form-item {
  padding-left: 24px;
  margin-bottom: 12px;
}

.mana-plan-form .sprot-form .ant-form-item {
  margin-bottom: 18px;
}

.template-col {
  padding: 6px 20px;
  cursor: pointer;
  border: 1px solid #e5e5e5;
  border-radius: 2px;
}

.template-col.template-col-active {
  color: #165dff;
  background: #e8f3ff;
  border: 1px solid #165dff;
  border-radius: 2px 0 0 2px;
}

.ai-health-content {
  min-height: 300px;
  max-height: 444px;
  padding: 16px;
  overflow: hidden auto;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
}

.ai-state-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
</style>
